package utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * @author admin
 */
public class HttpUtils {
    public static final String GET = "GET";
    public static final String POST = "POST";
    private static final String BODY_FORM_DATA = "FORM_DATA";
    private static final String BODY_JSON = "JSON";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    private static final String CONTENT_TYPE_JSON = "json";
    private static final String CONTENT_TYPE_FORM = "form";
    private static final String CONTENT_TYPE_XML = "xml";

    public static String sendRequest(String url, String method, String body, String header) {

        if (StringUtils.isEmpty(url) || StringUtils.isEmpty(method)) {
            throw new RuntimeException("请求地址和请求方法不能为空");
        }
        JsonNode headerJson = null;
        if (StringUtils.isNotEmpty(header)) {
            try {
                headerJson = objectMapper.readTree(header);
            } catch (IOException e) {
                throw new RuntimeException("header只支持json字符串");
            }
        }
        method = method.toUpperCase();
        if (GET.equals(method)) {
            JsonNode bodyJson = null;
            if (StringUtils.isNotEmpty(body)) {
                try {
                    bodyJson = objectMapper.readTree(body);
                } catch (IOException e) {
                    throw new RuntimeException("body只支持json字符串");
                }
            }
            return getMethod(url, bodyJson, headerJson);
        } else {
            return postMethod(url, body, headerJson);
        }
    }


    /**
     * Get方法
     */
    private static String getMethod(String url, JsonNode param, JsonNode header) {
        try {
            if (Objects.nonNull(param) && param.size() > 0) {
                Iterator<String> keys = param.fieldNames();
                StringBuilder urlBuilder = new StringBuilder(url);
                boolean first = true;
                while (keys.hasNext()) {
                    if (first) {
                        urlBuilder.append("?");
                        first = false;
                    } else {
                        urlBuilder.append("&");
                    }
                    String key = keys.next();
                    JsonNode valueJson = param.get(key);
                    String value = valueJson.asText();
                    urlBuilder.append(key).append("=").append(value);
                }
                url = urlBuilder.toString();
            }

            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(url);
                addHeader(header, httpGet);
                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("调用接口异常", e);
        }
    }

    private static String postMethod(String url, String body, JsonNode header) {
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpPost httpPost = new HttpPost(url);
                String contentType = addHeader(header, httpPost);
                if (CONTENT_TYPE_JSON.equals(contentType) || CONTENT_TYPE_XML.equals(contentType)) {
                    httpPost.setEntity(new StringEntity(body,"UTF-8"));
                } else if (CONTENT_TYPE_FORM.equals(contentType)) {
                    JsonNode bodyJson = null;
                    if (StringUtils.isNotEmpty(body)) {
                        try {
                            bodyJson = objectMapper.readTree(body);
                        } catch (IOException e) {
                            throw new RuntimeException("body只支持json字符串");
                        }
                    }
                    // 创建一个提交数据的容器
                    List<BasicNameValuePair> params = new ArrayList<>();
                    if (Objects.nonNull(bodyJson) && bodyJson.size() > 0) {
                        Iterator<String> keys = bodyJson.fieldNames();
                        while (keys.hasNext()) {
                            String key = keys.next();
                            params.add(new BasicNameValuePair(key, bodyJson.get(key).asText()));
                        }
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                }
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("调用接口异常", e);
        }
    }

    private static String addHeader(JsonNode header, HttpRequestBase httpPost) {
        String c = "Content-Type";
        String contentType = CONTENT_TYPE_JSON;
        if (Objects.nonNull(header) && header.size() > 0) {
            Iterator<String> keys = header.fieldNames();
            while (keys.hasNext()) {
                String key = keys.next();
                httpPost.addHeader(key, header.get(key).asText());
                if (c.equals(key)) {
                    if (header.get(key).asText().contains(CONTENT_TYPE_FORM)) {
                        contentType = CONTENT_TYPE_FORM;
                    } else if (header.get(key).asText().contains(CONTENT_TYPE_XML)) {
                        contentType = CONTENT_TYPE_XML;
                    }
                }
            }
        }
        return contentType;
    }

    /**
     * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常
     * 不用导入SSL证书
     *
     * @return  返回不校验证书的httpclient
     */
    public static CloseableHttpClient wrapClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                        throws java.security.cert.CertificateException {
                    // TODO Auto-generated method stub

                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                        throws java.security.cert.CertificateException {
                    // TODO Auto-generated method stub

                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    // TODO Auto-generated method stub
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
            return httpclient;
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpClients.createDefault();
        }
    }
}
